var debugMode = false;
var colorBlack = "rgb(0, 0, 0)";
var tictactoeController = null;

var TicTacToeGameController = function()
{
    // Verify preconditions.
    var domCanvas = $("canvas#gameboard")[0];
    if (domCanvas === null || typeof domCanvas !== "object")
    {
        throw new Error("A canvas element with an id of gameboard is required in the html for the game to function but it is missing.");
    }
      
    this.game = new Game(this);
    this.players = null;
    this.canvas = new Canvas(this.game.getBoard(), $(domCanvas));
    this.canvas.setupLayout();
    this.canvas.setupClick();
    this.canvas.setupDND();
    this.setupRestartButton();
    this.setupDebugCanvasMouseTracer();
}

TicTacToeGameController.prototype.setupRestartButton = function()
{
    var controller = this;
    $("button#restart").click
    (
        function()
        {
            controller.canvas.setupLayout();
            controller.startGame();
        }
    );
}

TicTacToeGameController.prototype.startGame = function()
{
    this.players = this.game.getPlayers();
    this.players[0].setName("Guest");
    this.players[1].setName("Machine");
    
    this.game.start(this.players[0]);  
    this.updateGamePlayersNames();
}

TicTacToeGameController.prototype.stopGame = function()
{
    this.game.stop();
}

TicTacToeGameController.prototype.updateGamePlayersNames = function()
{
   $("img#currentPlayerSymbol").attr("src", this.getCurrentPlayerImageSrc());
   $("div#gameTitle2").text(this.game.getCurrentPlayer().getName() + "'s Turn");    
}
    
TicTacToeGameController.prototype.setupDebugCanvasMouseTracer = function()
{
    if (debugMode == false)
    {
        $(".debugInfo").css("display", "none");
    }
    else
    {
        $(".debugInfo").css("display", "block");

        var jqDebugInfoXPos = $(".debugInfo #xPos");
        var jqDebugInfoYPos = $(".debugInfo #yPos");
        var theCanvasWrapper = this.canvas;

        theCanvasWrapper.jqCanvas.mousemove
        (
            function(event)
            {
                // http://jquery-howto.blogspot.com/2009/07/identifying-locating-mouse-position-in.html
                // Turns out that Firefox returns a float for offset().left/top.
                jqDebugInfoXPos.html(event.pageX - Math.floor(theCanvasWrapper.jqCanvas.offset().left)-1);
                jqDebugInfoYPos.html(event.pageY - Math.floor(theCanvasWrapper.jqCanvas.offset().top)-1);
            }
        );
    }
}

TicTacToeGameController.prototype.notifyIllegalMove = function(location)
{
    
}

TicTacToeGameController.prototype.notifyGameDraw = function(location)
{
    $("div#gameTitle2").text("Game's a draw."); 
}

TicTacToeGameController.prototype.notifyGameWin = function(location)
{
    $("div#gameTitle2").text(this.game.getWinnerPlayer().getName() + " won !!!");     
}

TicTacToeGameController.prototype.notifyGameMove = function(location)
{
    var image = document.createElement('img');
    image.src = this.getCurrentPlayerImageSrc();
    
    var theCanvasWrapper = this.canvas;
    
    $(image).load
    (
        function(event)
        {
            var domCanvas = (theCanvasWrapper.jqCanvas)[0];
            var context = domCanvas.getContext("2d");
            var positionY = location % 3 ? Math.floor(location / 3) : location / 3 - 1;
            var positionX = location % 3 ? location % 3 - 1 : 2;

            // http://stackoverflow.com/questions/318630/get-real-image-width-and-height-with-javascript-in-safari-chrome
            var xOffset = (theCanvasWrapper.boardPositionWidth - this.width)/2.0;
            var yOffset = (theCanvasWrapper.boardPositionHeight - this.height)/2.0;
            context.drawImage(image, positionX * theCanvasWrapper.boardPositionWidth + xOffset , positionY * theCanvasWrapper.boardPositionHeight + yOffset);
        }
    )    
}

TicTacToeGameController.prototype.notifyCurrentPlayerChanged = function()
{
    this.updateGamePlayersNames();
}

TicTacToeGameController.prototype.getCurrentPlayerImageSrc = function()
{
    return this.game.getCurrentPlayer().getType() === "X" ? 
                                        $("meta#playerXsymbol").attr("src") : 
                                        $("meta#playerYsymbol").attr("src");  
}

TicTacToeGameController.prototype.moveAtLocation = function(location)
{
    if (this.game.isStopped())
        return;

    this.game.makeMove(location);
}
    
TicTacToeGameController.prototype.uiMoveAtLocation = function(uiEevent)
{
    // TODO: implement this,
    // if (mGame.getCurrentPlayer() instanceof AIPlayer)
    //    return; // TODO: this should be an exception thrown.
        
    var theCanvas = this.canvas;
    var position = theCanvas.getEventDevIndPosition.call(theCanvas, uiEevent);
    var positionX = position[0];
    var positionY = position[1];
    var location = this.canvas.gameDivIndWidth * positionY + positionX + 1;
    if (debugMode)
        $("#location").html(location);
    this.moveAtLocation(location);
}

$(document).ready
(
    // Setup the game environment.
    function()
    {
        $("#gameTitles").css("display", "block").css("text-align", "center");
        $("#gameTitle1").css("display", "block").css("text-align", "center");
        $("#gameTitle2").css("display", "block").css("text-align", "center");
        $("div#tabTicTacToe").css("display", "block").css("width", "90%").css("margin", "auto").css("text-align", "center");;
        $("div#tabTicTacToe button#restart").css("display", "block").css("width", "auto").css("margin", "auto");
        $("div#tabTicTacToe canvas#gameboard").css("background-color", "green");
        $(".debugInfo").css("display", "block").css("margin-top", "3em");
        //$("div#tabWelcome").css("height", $("div#tabTicTacToe").height());
        $(".textRed").css("color", "red");
        $(".textBlue").css("color", "blue");
        
        $("#gameTitle1").css("font-family", "arial helvetica").css("font-size", "26px").css("font-weight", "bold");// .css("width", "600px").css("margin", "auto");
        $("#gameTitle2").css("font-family", "arial helvetica").css("font-size", "26px").css("font-weight", "bold");// .css("width", "600px").css("margin", "auto");

        tictactoeController = new TicTacToeGameController();
        tictactoeController.startGame();
    }
)